﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WSS.BLL.Xt;
using WSS.Models.User;
using WSS.Models.Xt;
using WSS.Pub;

namespace WSS.Web.Controllers
{
    public class XtController : MyController
    {
        //
        // GET: /Xt/

        [MyAuthorize]
        public ActionResult Permissions()
        {

            var list = DB.ListSod("LIST2_HOSP_HOSPITAL", null);

            ViewBag.SELECT_HOSPTIAL = list.ToSelectListItem("HOSP_ID", "HOSP_NAME");

            return View();
        }
        [MyAuthorize]
        public ActionResult Function()
        {
            return View();
        }
        [MyAuthorize]
        public ActionResult Menu()
        {
            return View();
        }

        public ActionResult Typeahead()
        {
            //   var param = new { WHERE_CLAUSE = " GN_MC LIKE '%" + query + "%' OR GN_ID LIKE '%" + query + "%' || OR JXM LIKE '%" + query + "%'" };
            var param = new { };
            var list = BLL.Xt.FunctionDb.Instance.GetList(param);
            return this.MyJson(list);

        }

        #region 菜单

        public ActionResult GetResCategoryBtnMenu()
        {
            var list = BLL.Xt.MenuDb.Instance.GetList(new { USER_ID = AccountCache.UserId, FALG_INVALID = 0, ORDER_BY_CLAUSE = "CD_LEVEL,ORDER_NO" });
            StringBuilder html = new StringBuilder();

            if (list.Count > 0)
            {
                if (Request.Req("selectall") == "1")
                {
                    html.AppendLine("<li><a href=\"#\" onclick='on_rescate_menu_click(\"\",\"全部\")'>选择全部</a></li>");
                    html.AppendLine("<li class=\"divider\"></li>");
                }
                get_res_cate_button_menu(ref html, "ROOT", list);
            }
            else
            {
                html.AppendLine("<li><a href=\"/rescenter/category\">您没有设置菜单，现在设置</a></li>");
            }
            return Content(html.ToString());
        }

        public ActionResult AddCategory()
        {
            var order = Request.Req("orderno");
            var catename = Request.Req("catename");
            var parentno = Request.Req("parentno");
            var level = Request.Req("level");

            if (catename.IsNullOrEmpty() || parentno.IsNullOrEmpty() || order.IsNullOrEmpty())
            {
                return this.MyJson(false, "菜单新增失败，缺少参数");
            }

            var listdb = new List<DBState>();

            XT_CDB model = new XT_CDB();
            model.CD_MC = Request.Req("catename");
            model.ORDER_NO = order.IsNumeric() ? int.Parse(order) : 12;
            model.CD_PID = parentno;
            model.FLAG_INVALID = 0;
            model.CD_GNID = "NONE";
            model.CD_ID = BLL.Xt.XhbManager.Instance.GetXh(model.GetTableName());
            model.FLAG_LAST = 1;
            model.JXM = "aa";
            model.CD_LEVEL = int.Parse(level);

            if (model.CD_PID != "ROOT")
            {
                XT_CDB parentmodel = MenuDb.Instance.GetOne(model.CD_PID);
                parentmodel.FLAG_LAST = 0;
                listdb.Add(new DBState { Name = parentmodel.MAP_UPDATE, Param = parentmodel, Type = ESqlType.UPDATE });
            }
            listdb.Add(new DBState { Name = model.MAP_INSERT, Param = model, Type = ESqlType.INSERT });
            DB.Execute(listdb);

            return this.MyJson(true, model.CD_ID);
        }

        public ActionResult RenameCateName()
        {
            string cateno = Request.Req("cateno"),
                newname = Request.Req("newname");

            try
            {
                var dbinstance = BLL.Xt.MenuDb.Instance;
                var model = dbinstance.GetOne(cateno);
                model.CD_MC = newname;
                dbinstance.Update(model);
                return this.MyJson(true, "菜单重命名成功");
            }
            catch (Exception ex)
            {
                return this.MyJson(false, "菜单重命名失败");
            }
        }

        public ActionResult RemoveCate()
        {
            string cateno = Request.Req("cateno");

            try
            {
                var dbinstance = BLL.Xt.MenuDb.Instance;
                var userid = AccountCache.UserId;

                var model = dbinstance.GetOne(cateno);

                if (model == null || model.CD_ID == null)
                {
                    return this.MyJson(false, "菜单不存在，刷新页面后再看看吧");
                }

                if (model.FLAG_LAST == 0)
                {
                    return this.MyJson(false, "只能移除末级的菜单");
                }

                if (model.CD_GNID.ToUpper() != "NONE")
                {
                    return this.MyJson(false, "该菜单已经绑定功能，不能随意移除");
                }

                var listdb = new List<DBState>();

                if (model.CD_PID != "ROOT")
                {
                    var siblings = dbinstance.GetList(new { CD_ID = model.CD_PID, FLAG_INVALID = 0, USER_ID = userid });
                    if (siblings.Count == 1)
                    {
                        var paentmodel = dbinstance.GetOne(model.CD_PID);
                        paentmodel.FLAG_LAST = 1;
                        listdb.Add(new DBState { Name = paentmodel.MAP_UPDATE, Param = paentmodel, Type = ESqlType.UPDATE });
                    }
                }
                listdb.Add(new DBState { Name = model.MAP_DELETE, Param = model, Type = ESqlType.DELETE });

                DB.Execute(listdb);

                return this.MyJson(true, "菜单移除成功");
            }
            catch (Exception ex)
            {
                return this.MyJson(false, "菜单移除失败");
            }
        }

        public ActionResult SaveMenuOrder(string ids, string orders)
        {
            if (ids.IsNullOrEmpty())
            {
                return this.MyJson(false, "缺少菜单ID参数");
            }
            if (orders.IsNullOrEmpty())
            {
                return this.MyJson(false, "缺少排序值参数");
            }
            ids = ids.TrimEnd(',');
            orders = orders.TrimEnd(',');

            var arrid = ids.Split(',');
            var arrorder = orders.Split(',');

            if (arrid.Length != arrorder.Length)
            {
                return this.MyJson(false, "菜单ID参数与排序值参数数目不一样多");
            }

            var sqls = new List<string>();
            for (int i = 0, len = arrid.Length; i < len; i++)
            {
                sqls.Add("UPDATE XT_CDB SET ORDER_NO = '" + arrorder[i] + "' WHERE CD_ID = '" + arrid[i] + "'");
            }

            DB.Execute(sqls);
            return this.MyJson(true, "保存成功");
        }

        public ContentResult GetResCateGrid()
        {
            var list = BLL.Xt.MenuDb.Instance.GetList(new { ORDER_BY_CLAUSE = "CD_LEVEL,ORDER_NO" });
            StringBuilder html = new StringBuilder();
            if (list.Count > 0)
            {
                get_res_cate_grid(ref html, "ROOT", list);
            }
            return Content(html.ToString());
        }

        public ActionResult MenuSetting(string menuid)
        {
            var menu = MenuDb.Instance.GetOne(menuid) ?? new Models.Xt.XT_CDB();
            ViewData.Model = menu;
            return View();
        }

        public ActionResult SaveSetting()
        {
            string cd_id = Request.Req("cd_id");
            string cd_bkcolor = Request.Req("cd_bkcolor");
            string cd_icon = Request.Req("cd_icon");

            var inst = MenuDb.Instance;
            var model = inst.GetOne(cd_id);
            model.CD_ICON = cd_icon;
            model.CD_BKCOLOR = cd_bkcolor;
            inst.Update(model);
            return this.MyJson(true, "保存成功");
        }

        public ActionResult MenuLinkToFunction(string menuid)
        {
            ViewBag.MENUID = menuid;
            return View();
        }
        public ActionResult SaveMenuLinktoFunction(string menuid, string fnid)
        {
            if (menuid.IsNullOrEmpty())
            {
                return this.MyJson(false, "菜单编号参数不允许为空");
            }
            if (fnid.IsNullOrEmpty())
            {
                return this.MyJson(false, "功能编号参数不允许为空");
            }
            var inst = BLL.Xt.MenuDb.Instance;
            var menumodel = inst.GetOne(menuid);
            if (menumodel != null && menumodel.CD_ID != null)
            {
                menumodel.CD_GNID = fnid;
                inst.Update(menumodel);
                return this.MyJson(true, "操作成功");
            }
            else
            {
                return this.MyJson(false, "错误的菜单编号，该菜单可能已经被删除，请刷新后重试");
            }
        }

        /// <summary>
        /// 前端管理菜单需要
        /// </summary>
        /// <param name="html"></param>
        /// <param name="parentno"></param>
        /// <param name="datas"></param>
        private void get_res_cate_grid(ref StringBuilder html, string parentno, IEnumerable<XT_CDB> datas)
        {
            var subdatas = datas.Where(t => t.CD_PID == parentno).ToList();

            foreach (XT_CDB category in subdatas)
            {
                html.AppendLine("<li class=\"list-group-item\" style=\"margin-left:" + category.CD_LEVEL * 50 + "px;\" data-cateno=\"" + category.CD_ID + "\" data-lvl=\"" + category.CD_LEVEL + "\" data-gnid=\"" + category.CD_GNID + "\">");
                html.AppendLine("<label>" + category.CD_MC + "</label>");
                html.AppendLine("<span class=\"pull-right close\" onclick=\"removecate(this);\">&times;</span >");
                html.AppendLine("</li>");

                if (category.FLAG_LAST != 1)
                {
                    get_res_cate_grid(ref html, category.CD_ID, datas);
                }
            }
        }

        /// <summary>
        /// 前端按钮下拉菜单需要
        /// </summary>
        /// <param name="html"></param>
        /// <param name="parentno"></param>
        /// <param name="datas"></param>
        private void get_res_cate_button_menu(ref StringBuilder html, string parentno, IEnumerable<XT_CDB> datas)
        {
            var subdatas = datas.Where(t => t.CD_PID == parentno);

            foreach (XT_CDB category in subdatas)
            {
                html.AppendLine("<li data-cateno='" + category.CD_ID + "'>");
                html.AppendLine("<a href='#' style='margin-left:" + category.CD_LEVEL * 10 + "px;' onclick='on_rescate_menu_click(\"" + category.CD_ID + "\",\"" + category.CD_MC + "\")'>" + category.CD_MC + "</a>");
                html.AppendLine("</li>");

                if (category.FLAG_LAST != 1)
                {
                    get_res_cate_button_menu(ref html, category.CD_ID, datas);
                }
            }
        }

        /// <summary>
        /// 递归取得所有的子菜单编号
        /// </summary>
        /// <param name="listnos"></param>
        /// <param name="parentno"></param>
        /// <param name="datas"></param>
        private void get_res_cateno_children(ref List<string> listnos, string parentno, IEnumerable<XT_CDB> datas)
        {
            var subdatas = datas.Where(t => t.CD_PID == parentno);

            foreach (XT_CDB category in subdatas)
            {
                listnos.Add(category.CD_ID);

                if (category.FLAG_LAST != 1)
                {
                    get_res_cateno_children(ref listnos, category.CD_ID, datas);
                }
            }
        }


        #endregion

        #region 功能

        public ActionResult FnList()
        {
            var param = new StrObjDict();

            var sch_keyword = Request.Req("sch_keyword");
            if (!sch_keyword.IsNullOrEmpty())
            {
                param.Merger(
                    new
                    {
                        WHERE_CLAUSE = "GN_ID LIKE '%" + sch_keyword + "%' OR GN_MC LIKE '%" + sch_keyword + "%'"
                    });
            }

            var list = BLL.Xt.FunctionDb.Instance.GetList(param);
            return this.MyJson(Paginator.Page<XT_GNB>(list));
        }

        public ActionResult FnAdd(XT_GNB model)
        {
            return _SaveFn(model, true);
        }
        public ActionResult FnEdit(XT_GNB model)
        {
            return _SaveFn(model, false);
        }
        private ActionResult _SaveFn(XT_GNB model, bool is_add)
        {
            if (model.GN_MC.IsNullOrEmpty())
            {
                return this.MyJson(false, "功能名称不允许为空");
            }
            if (model.GN_CONTROLLER.IsNullOrEmpty())
            {
                return this.MyJson(false, "CONTROLLER不允许为空");
            }
            if (model.GN_ACTION.IsNullOrEmpty())
            {
                return this.MyJson(false, "CONTROLLER不允许为空");
            }
            if (model.JXM.IsNullOrEmpty())
            {
                return this.MyJson(false, "简写码不允许为空");
            }
            if (is_add)
            {
                model.GN_ID = BLL.Xt.XhbManager.Instance.GetXh(model.GetTableName());

                BLL.Xt.FunctionDb.Instance.Insert(model);
                return this.MyJson(true, "新增成功");
            }
            else
            {
                BLL.Xt.FunctionDb.Instance.Update(model);
                return this.MyJson(true, "编辑成功");
            }


        }
        #endregion

        #region 权限

        public ActionResult UserGroupList()
        {
            string hospitalid = Request.Req("HOSPID");
            if (hospitalid.IsNullOrEmpty())
            {
                throw new Exception("医院ID参数不允许为空");
            }
            var list = DB.List<USER_GROUP>(new { HOSP_ID = hospitalid }.ToStrObjDict());
            return this.MyJson(new { rows = list });
        }

        public ActionResult UserGroupMemberList()
        {
            string groupid = Request.Req("GRPID");
            if (groupid.IsNullOrEmpty())
            {
                groupid = "-1";
            }

            string sql =
                "select m.user_id,u.user_no,u.user_name from user_group_member m left join user_user u on m.user_id = u.user_id";
            sql += " where m.user_group_id = '" + groupid + "'";

            return this.MyJson(new { rows = DB.Select(sql) });
        }

        public ActionResult UserGroupMemberList_Not()
        {
            string hospitalid = Request.Req("HOSPID");
            string groupid = Request.Req("GRPID");

            if (hospitalid.IsNullOrEmpty())
            {
                throw new Exception("医院ID参数不允许为空");
            }

            if (groupid.IsNullOrEmpty())
            {
                groupid = "-1";
            }
            string sql = @"select u.user_id,u.user_name,u.user_no from user_user u
where u.flag_login = '1' and hosp_id = '{0}' and u.user_id not in (
select m.user_id from user_group_member m where m.user_group_id = '{1}'
)";
            sql = string.Format(sql, hospitalid, groupid);

            return this.MyJson(new { rows = DB.Select(sql) });

        }

        public ActionResult SaveInsertUgpm()
        {
            string grpid, userid;
            grpid = Request.Req("grpid");
            userid = Request.Req("userid");

            if (grpid.IsNullOrEmpty())
            {
                throw new Exception("用户组ID参数不允许为空");
            }

            if (userid.IsNullOrEmpty())
            {
                throw new Exception("用户ID参数不允许为空");
            }

            USER_GROUP_MEMBER model = new USER_GROUP_MEMBER();
            model.USER_GROUP_ID = grpid;
            model.USER_ID = userid;

            DB.Execute(new DBState { Name = model.MAP_INSERT, Param = model, Type = ESqlType.INSERT });
            return this.MyJson(true);
        }

        public ActionResult SaveAddUserGroup()
        {
            string grpname = Request.Req("grpname"),
                hospid = Request.Req("hospid");

            if (hospid.IsNullOrEmpty())
            {
                return this.MyJson(false, "缺少医院ID参数");
            }
            if (grpname.IsNullOrEmpty())
            {
                return this.MyJson(false, "缺少分组名称参数");
            }

            USER_GROUP model = new USER_GROUP();
            model.FLAG_INVALID = 0;
            model.HOSP_ID = hospid;
            model.ORDER_NO = 10;
            model.USER_GROUP_ID = BLL.Xt.XhbManager.Instance.GetXh(model.GetTableName());
            model.USER_GROUP_NAME = grpname;
            DB.Execute(new DBState
            {
                Name = model.MAP_INSERT,
                Param = model,
                Type = ESqlType.INSERT
            });
            return this.MyJson(true, "新增成功");
        }

        #endregion
    }
}
